package com.df.happylearn.request;

import com.df.happylearn.model.Article;
import com.df.happylearn.model.ArticleContent;

import java.util.List;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by dingfeng on 2016/8/12.
 */
public class DataRequest {
    private static DataRequest instance;
    private Retrofit mRetrofit;
    private ApiService mApiService;

    public static synchronized DataRequest getInstance() {
        if (instance == null) {
            instance = new DataRequest();
        }
        return instance;
    }

    private DataRequest() {
        mRetrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(RetrofitUtil.genericClient())
                .build();
        mApiService = mRetrofit.create(ApiService.class);
    }

    private class HttpResultFunc<T> implements Func1<HttpResult<T>, T> {

        @Override
        public T call(HttpResult<T> httpResult) {
            if (httpResult.getData() != null) {
                return httpResult.getData();
            } else {
                throw new ServerException("Get data failed!");
            }
        }
    }

    public void getArticle(Subscriber<List<Article>> subscriber, int cat_id, int page, int size) {
        mApiService.getArticle(cat_id, page, size)
                .map(new HttpResultFunc<List<Article>>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public void getArticleContent(Subscriber<ArticleContent> subscriber, int article_id) {
        mApiService.getArticleContent(article_id)
                .map(new HttpResultFunc<ArticleContent>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }



}
